<?php


class NumberingHelper extends AppHelper
{
    var $numbering = array();
    
    /*
     * Takes an array of levels and return proper numbering 
     * Returns an array
     */ 
    function initiate($ids){
        $i = 1;

        foreach ($ids as $id => $level) {
            if ($level == '0') {
                $this->numbering[$id][0] = $i++;
            } else if ($level > $prevlevel) {
                $this->numbering[$id][0] = $this->numbering[$previd][0];
                $k = 1;
                for ($j=1; $j<=$level; $j++) {
                    if (isset($this->numbering[$previd][$j])) $this->numbering[$id][$j] = $this->numbering[$previd][$j];
                    else $this->numbering[$id][$j] = $k++;
                }
            } else if ($level == $prevlevel) {
                $this->numbering[$id][0] = $this->numbering[$previd][0];
                for ($j=1; $j<=$level; $j++) {
                    if (isset($this->numbering[$previd][$j])) $this->numbering[$id][$j] = $this->numbering[$previd][$j];
                    if ($j == $level) $this->numbering[$id][$j] = $this->numbering[$previd][$j]+ 1;
                }
            } else if ($level < $prevlevel) {
                $this->numbering[$id][0] = $this->numbering[$previd][0];
                for ($j=1; $j<=$level; $j++) {
                    if ($j == $level) {
                        $this->numbering[$id][$j] = $this->numbering[$previd][$j] + 1;
                    }else{
                        $this->numbering[$id][$j] = $this->numbering[$previd][$j] ;
                    }
                }
            }
            
            $prevlevel = $level;
            $previd = $id;
        }
        return $this->numbering;
    }
    
    /*
     * Returns strings for numbering
     */
    function buildstring($ids) {
        $num = $this->initiate($ids);
        $numstring = array();
            
        foreach ($num as $id=>$level) {
            $numstring[$id] = '';
            foreach ($level as $key=>$value) {
                $numstring[$id] = $numstring[$id].$value.'.';
            }
            //$numstring[$id] = substr($numstring[$id], 0, -1); // strip last character
        }
        return $numstring;
    }
}
?>
